﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System.IdentityModel.Tokens.Jwt;
using Warehouse.Services.Repository;
using WCS.Entities;
using WCS.Entities.Api;
using WCS.Entities.User;

namespace WCS.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IMemoryCache cache;
        private readonly Repository<UserInfo> userInfoRepository;

        public UserController(IMemoryCache cache, Repository<UserInfo> userInfoRepository)
        {
            this.cache = cache;
            this.userInfoRepository = userInfoRepository;
        }


        #region 创建


        /// <summary>
        /// 创建用户信息
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<ApiResult>> Create([FromBody] UserInfo userInfo)
        {
            try
            {
                userInfo.Password = MD5Utils.Md5(userInfo.Password);
                bool b = await userInfoRepository.AddAsync(userInfo);
                if (!b)
                    return ApiResultHelp.Error("添加失败，服务器发生错误");
                return ApiResultHelp.Success(userInfo);
            }
            catch (Exception ex)
            {
                return ApiResultHelp.Error($"添加出错!服务器发生错误:{ex.Message}");
            }


        }
        #endregion

        #region 更新
        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="id">Park的Id</param>
        /// <param name="parkInfo">新的Park点信息</param>
        /// <returns></returns>

        [HttpPut("{id}")]
        public async Task<ApiResult> Update(string id, UserInfo UserInfo)
        {

            var oldUser = await userInfoRepository.FindAsync(id);
            if (oldUser == null)
                return ApiResultHelp.Error("没有找到该用户");

            UserInfo.Password = MD5Utils.Md5(UserInfo.Password);
            bool b = await userInfoRepository.UpdateAsync(UserInfo);
            if (!b)
                return ApiResultHelp.Error("修改失败");
            return ApiResultHelp.Success(UserInfo);
        }

        [HttpPut()]
        public async Task<ApiResult> Password([FromServices] IHttpContextAccessor accessor, PasswordInfo info)
        {
            var claim = accessor?.HttpContext?.User?.FindFirst(JwtRegisteredClaimNames.Jti);
            if (claim == null)
                return ApiResultHelp.Error("token已经过期请重新登录");

            if (string.IsNullOrEmpty(claim.Value))
            {
                return ApiResultHelp.Error("无法找到Id");
            }

            var user = await userInfoRepository.FindAsync(int.Parse(claim.Value));


            if (user.Password != MD5Utils.Md5(info.Password))
                return ApiResultHelp.Error("密码不对!");
            else
            {
                user.Password = MD5Utils.Md5(info.NewPassword);
                var b = await userInfoRepository.UpdateAsync(user);
                if (!b)
                    return ApiResultHelp.Error("更新出错!");
            }
            return ApiResultHelp.Success();
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除单个用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult<ApiResult>> Delete(string id)
        {
            var user = await userInfoRepository.FindAsync(id);
            if (user == null)
                return ApiResultHelp.Error("用户不存在!");
            if (user.UserName == "Admin")
                return ApiResultHelp.Error("默认管理员不可删除!");
            bool b = await userInfoRepository.DeleteByIdAsync(id);
            if (!b)
                return ApiResultHelp.Error("删除失败");

            return ApiResultHelp.Success(b);
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids">要删除的Ids</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ActionResult<ApiResult>> DeleteByIds(dynamic[] ids)
        {

            var id = ids.Where(x => x.ToString() != "1").ToArray();
            if (id.Length == 0)
                return ApiResultHelp.Error("默认管理员不可删除!");

            bool b = await userInfoRepository.DeleteByIdsAsync(id);
            if (!b)
                return ApiResultHelp.Error("删除失败");
            return ApiResultHelp.Success(b);
        }
        #endregion

        #region 查找 

        /// <summary>
        /// 查询单个用户信息
        /// </summary>
        /// <param name="accessor"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public async Task<ApiResult> Info([FromServices] IHttpContextAccessor accessor)
        {

            var claim = accessor?.HttpContext?.User?.FindFirst(JwtRegisteredClaimNames.Jti);
            if (claim == null)
                return ApiResultHelp.Error("token已经过期请重新登录");

            if (string.IsNullOrEmpty(claim.Value))
            {
                return ApiResultHelp.Error("无法找到Id");
            }

            var user = await userInfoRepository.FindAsync(int.Parse(claim.Value));

            return ApiResultHelp.Success(user);
        }
        /// <summary>
        /// 分页查找
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="limit">每页大小</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetUserByPage(int page, int limit, [FromQuery] string query)
        {
            RefAsync<int> total = 0;
            try
            {
                if (query != null)
                {
                    JObject jobject = JObject.Parse(query);
                    List<IConditionalModel> models = new List<IConditionalModel>();
                    foreach (var key in jobject.Properties())
                    {

                        if (string.IsNullOrEmpty(key.Value.ToString()) || key.Value.ToString() == "0")
                            continue;

                        models.Add(new ConditionalModel()
                        { FieldName = key.Name, FieldValue = key.Value.ToString(), ConditionalType = ConditionalType.Equal });
                    }
                    var users = await userInfoRepository.QueryAsync(models, page, limit, total);
                    return ApiResultHelp.Success(new { list = users, total = total.Value });

                }
                else
                {
                    var users = await userInfoRepository.QueryAsync(page, limit, total);
                    return ApiResultHelp.Success(new { list = users, total = total.Value });

                }
            }
            catch (Exception ex)
            {
                return ApiResultHelp.Error($"查询出错:{ex.Message}");
            }
        }

        /// <summary>
        /// 是否存在设备
        /// </summary>
        /// <returns></returns>
        [HttpGet()]
        public async Task<ActionResult<ApiResult>> Check([FromQuery] string query)
        {
            JObject jobject = JObject.Parse(query);
            try
            {
                List<IConditionalModel> models = new List<IConditionalModel>();

                foreach (var key in jobject.Properties())
                {
                    if (key.Name.ToString() == "id" && jobject.Count > 1)
                        continue;
                    else
                        models.Add(new ConditionalModel()
                        {
                            FieldName = key.Name,
                            FieldValue = key.Value.ToString(),
                            ConditionalType = ConditionalType.Equal
                        });
                }
                var user = await userInfoRepository.Context.Queryable<UserInfo>().Where(models).ToListAsync();
                if (jobject.ContainsKey("id") && jobject.Count > 1)
                {
                    var count = user.Count(x => x.UserId.ToString() != jobject["id"].ToString());
                    return ApiResultHelp.Success(count);
                }


                return ApiResultHelp.Success(user.Count);

            }
            catch (Exception e)
            {
                return ApiResultHelp.Error("查找用户失败" + e.Message);
            }

        }

        [HttpGet]
        public async Task<ApiResult> GetRoles()
        {

            Dictionary<string, int> types = new Dictionary<string, int>();
            await Task.Run(() =>
            {
                foreach (Role value in Enum.GetValues(typeof(Role)))
                {
                    types.Add(value.ToString(), (int)value);
                }
            });


            return ApiResultHelp.Success(types.ToArray());

        }

        #endregion

    }
}
